var baseUrl = 'https://table.shangqihang.com/qhApi1/';
var baseUrl1 = 'https://table.shangqihang.com/qhApi2/';
var baseWebsocketUrl = 'wss://table.shangqihang.com/qhApi2/common/webSocket/';

// if (process.env.NODE_ENV === 'development') {
// 	// 开发环境
// 	baseUrl = 'https://test-table.shangqihang.com/qhApi1/'
// 	baseUrl1 = 'https://test-table.shangqihang.com/qhApi2/'
// 	baseWebsocketUrl = 'ws://test-table.shangqihang.com/qhApi2/common/webSocket/';
// }
var terminaltype=''
// #ifdef MP-WEIXIN
terminaltype = 2
// #endif

// #ifdef MP-TOUTIAO
terminaltype = 5
// #endif

let productId='15' //13记单词 15专升本
var lastTime=0 //函数节流

let response = function(res,otherParams){
	if(res&&(res.code==9999||res.code==401||res.code==200000)){
		// console.log('res=',res)
		if(otherParams.isLogin!==false){
			// console.log('(otherParams.isLogin=',otherParams.isLogin)
			let tokenValue=uni.getStorageSync("tokenValue");
			// 存在本地token，是老用户，进行尝试自动登录
			if(tokenValue) {
				let nowTime=Date.now()
				if(nowTime-lastTime>1100) {
					autoLogin()
				}
				lastTime=nowTime	
			}else {
				uni.showToast({
					title:'未登录',
					icon:'none'
				})
				uni.clearStorageSync();
				setTimeout(()=>{
					uni.navigateTo({
						url: '/pages/login/login'
					})
				},1500)
			}
		}
	}
	return res;
}


const post= (url,data={},type)=>{
	let baseurl=baseUrl1;
	if(type){
		baseurl=baseUrl;
	}
	return uni.request({
		url: baseurl+url,
		data:data,
		method:'POST',
		header: {
			"content-type": "application/json",
			"loginType":'user',
			"productId":productId,
			"terminalType":terminaltype,
			"saToken":uni.getStorageSync('tokenValue')||''
		},
		dataType: "string",
		responseType: "text",
	}).then(res =>{
		if(res.statusCode !== 200) {
			uni.showToast({
				title:'数据异常',
				icon:'none'
			})
		}
		return response(JSON.parse(res.data)); 
	})
}

const autoLogin= ()=>{
	uni.login({
		success: async (loginRes) => {
			// console.log('loginRes',loginRes)
			var url = "";
			// #ifdef MP-WEIXIN
			url = "api/user/wechat/applet/login";
			// #endif

			// #ifdef MP-TOUTIAO
			url = "api/user/douyin/applet/login";
			// #endif
			const { code, data } = await post(
				url,
				{
					code: loginRes.code,
				},
				1
			);
			// if (code === -1) {
			// 	uni.clearStorageSync();
			// }
			if (code === 200) {
				uni.setStorageSync("tokenValue", data.tokenValue);
				//重新加载当前页面
				var pages = getCurrentPages()
				// console.log('pages=', pages)
				let fullPath=pages.at(-1).$page.fullPath
				console.log('fullPath=', fullPath)
				if(['/pages/index/index','/pages/mine/mine'].includes(fullPath)) {
					uni.reLaunch({
						url:fullPath
					})
				}else {
					uni.redirectTo({
						url:fullPath
					})
				}
				
				
				
			}
		},
	});
}

export default{
	post(url,data={},type,headerType){
		let baseurl=baseUrl1;
		if(type){
			baseurl=baseUrl;
		}
		headerType = headerType ? 'application/x-www-form-urlencoded' : 'application/json'
		return uni.request({
			url: baseurl+url,
			data:data,
			method:'POST',
			header: {
				"content-type": headerType,
				"loginType":'user',
				"productId":productId,
				"terminalType":terminaltype,
				"saToken":uni.getStorageSync('tokenValue')||''
			},
			dataType: "string",
			responseType: "text",
		}).then(res =>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
			}
			return response(JSON.parse(res.data)); 
		})
	},
	get1(url,data={},type,otherParams={}){
		let baseurl=baseUrl1;
		if(type){
			let baseurl=baseUrl;
		}
		return uni.request({
			url: baseurl+url,
			data:data,
			method:'GET',
			header:  {
				"content-type": "application/json",
				"loginType":'user',
				"productId":'13',
				"terminalType":terminaltype,
				"saToken":uni.getStorageSync('tokenValue')||''
			},
			dataType: "string",
			responseType: "text",
		}).then(res =>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
			}
			let data1='';
			if(res.data?.constructor== Object){
				data1=res.data;
			}else{
				data1=JSON.parse(res.data)
			}
			return response(data1,otherParams);
		})
	},
	gettts(url,data={},type){
		let baseurl=baseUrl1;
		if(type){
			let baseurl=baseUrl;
		}
		return uni.request({
			url: baseurl+url,
			data:data,
			method:'GET',
			header:  {
				"content-type": "application/json",
				"loginType":'user',
				"productId":productId,
				"terminalType":terminaltype,
				"saToken":uni.getStorageSync('tokenValue')||''
			},
			dataType: "string",
			responseType: "arraybuffer",
		}).then(res =>{
			if(res.statusCode !== 200) {
				
			}
			return response(res.data);
		})
	},
	get(url,data={}){
		return uni.request({
			url: baseUrl+url,
			data:data,
			method:'GET',
			header:  {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
				"content-type": "application/json",
				"loginType":'user',
				"productId":productId,
				"terminalType":terminaltype,
				"saToken":uni.getStorageSync('tokenValue')||''
			}
		}).then(res =>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
			}
			return response(JSON.parse(res.data));
		})
	},
	put(url,data={},type,headerType){
		let baseurl=baseUrl1;
		if(type){
			let baseurl=baseUrl;
		}
		headerType = headerType ? headerType : 'application/x-www-form-urlencoded;charset=utf-8'
		return uni.request({
			url: baseurl+url,
			data:data,
			method:'PUT',
			header:  {
				'Content-Type': headerType,
				"loginType":'user',
				"productId":productId,
				"terminalType":terminaltype,
				"saToken":uni.getStorageSync('tokenValue')||''
			}
		}).then(res =>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
			}
			return response(res.data);
		})
	},
	delete(url,data={},type){
		let baseurl=baseUrl1;
		if(type){
			let baseurl=baseUrl;
		}
		return uni.request({
			url: baseurl+url,
			data:data,
			method:'DELETE',
			header:  {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
				"content-type": "application/json",
				"loginType":'user',
				"productId":productId,
				"terminalType":terminaltype,
				"saToken":uni.getStorageSync('tokenValue')||''
			}
		}).then(res =>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
			}
			return response(res.data);
		})
	},
	uploadImg(url,data={}){
		return uni.uploadFile({
			  url: baseUrl+url,   //后端用于处理图片并返回图片地址的接口
			  filePath: data,
			  name: 'files',
			  header: {
			  	'Content-Type': 'multipart/form-data',
			  },
		}).then(res=>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
			}
			return response(res.data);
		})
	},
	ossUpload(file,obj){
		let filePath=file.url;
		var pos = (file.url).lastIndexOf('.')
		var suffix = ''
		if (pos !== -1) {
			suffix = (file.url).substring(pos)
		}
		var filename = new Date().getTime()+suffix
		let key = obj.dir+filename
		return uni.uploadFile({
			url: obj.host, //阿里云的存储地址，可以后端返回给你，也可以前端自己写上
			filePath, //要上传的临时文件路径
			name: 'file',
			formData: {
				key, //文件名
				accessid:obj.accessid,
				policy: obj.policy, //后台获取超时时间
				OSSAccessKeyId: obj.accessid, //后台获取临时ID
				success_action_status: '200', //让服务端返回200,不然，默认会返回204
				signature: obj.signature //后台获取签名
			}
		}).then(res=>{
			if(res.statusCode !== 200) {
				uni.showToast({
					title:'数据异常',
					icon:'none'
				})
				return;
			}
			res.data={
				url:obj.host + '/' + obj.dir + filename
			}
			return response(res.data);
		}).catch(err=>{
			console.log('错误：',err)
		})
	},
	baseUrl,
	baseWebsocketUrl
}

